package cn.wolfcode.listener;

import cn.wolfcode.cache.IStrategyCommentRedisService;
import cn.wolfcode.cache.vo.StrategyStatisVO;
import cn.wolfcode.domain.Strategy;
import cn.wolfcode.service.IStrategyService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 监听器
 * 执行redis 数据初始化
 * 实现类的泛型指的是 当监听器监听到此泛型所执行的方法时执行数据初始化逻辑
 */
//@Component
public class RedisDataInitListener implements ApplicationListener<ContextRefreshedEvent>{

    @Autowired
    private IStrategyService strategyService;
    @Autowired
    private IStrategyCommentRedisService strategyCommentRedisService;
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {


        //1:获取所有的攻略
        List<Strategy> strategies = strategyService.listAll();
        for (Strategy strategy : strategies) {
            //做判断 如果重启服务器时,已经初始化过了
            if (strategyCommentRedisService.isStrategyExists(strategy.getId())){
                continue;
            }
            //2:得到vo对象
            StrategyStatisVO vo = new StrategyStatisVO();
            //3:遍历所有攻略 把数据赋值给vo对象
            BeanUtils.copyProperties(strategy,vo);
            vo.setStrategyId(strategy.getId());
            //4:更新redis
            strategyCommentRedisService.setStrategyVO(vo);
        }

    }
}
